<template>
  <div>
    <el-dialog title="分配角色" :visible.sync="rolesVisible" width="50%" @close="RolesSettingClose">
      <!-- form主体内容 -->
      <el-form :model="userData" ref="rolesSettingFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username" size="small">
          <el-input v-model="userData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前角色" prop="password" size="small">
          <el-input v-model="userData.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配角色" size="small">
          <el-select v-model="rolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- form底部按钮 -->
      <span slot="footer">
        <el-button @click="rolesVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["userData", "rolesList"],
  data() {
    return {
      rolesSettingFormRules: {},
      rolesSettingForm: {},
      rolesVisible: false,
      rolesId: "",
    };
  },
  created() {},
  methods: {
    // 显示弹出框
    showDialog() {
      this.rolesVisible = true;
    },
    // 监听分配角色的关闭事件，重置表单
    RolesSettingClose() {
      this.rolesId = "";

      this.rolesVisible = false;
    },
    // 角色分配成功提交
    submitForm() {
      if (!this.rolesId) {
        this.$message.error("请选择分配的角色");
      } else {
        this.$axios
          .put(`users/${this.userData.id}/role`, { rid: this.rolesId })
          .then((res) => {
            if (res.data.meta.status == 200) {
              this.$message.success("分配角色成功");
              this.$emit("refreshData", true);
              this.rolesVisible = false;
            } else {
              this.$message.error("分配角色失败");
            }
          })
          .catch((error) => {
            console.log(error); //cathch用于处理错误事件
          });
      }
    },
  },
};
</script>
 
<style scoped>
</style>